package handler

import (
	"art-sys/cache"
	"art-sys/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func OrderById(c *gin.Context) {
	id := c.Query("id")
	var order []model.RepoOrder
	model.DB.Where("id=?", id).Find(&order)
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "查询成功",
		"data": order,
	})
	return
}

func OrderList(c *gin.Context) {
	var order []model.RepoOrder
	redis_key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "查询成功",
		"data": order,
	})
	return
}

func RepoOrderAdd(c *gin.Context) {
	repoId, _ := strconv.Atoi(c.PostForm("repoId"))
	orderNum, _ := strconv.Atoi(c.PostForm("orderNum"))
	orderPrice, _ := strconv.Atoi(c.PostForm("orderPrice"))
	if repoId == 0 || orderNum == 0 || orderPrice == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为0",
		})
		return
	}
	data := model.RepoOrder{
		RepoId:     repoId,
		OrderNum:   orderNum,
		OrderPrice: orderPrice,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "入库订单添加失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "入库订单添加成功",
		})
		return
	}
}

func RepoAdd(c *gin.Context) {
	repoCode := c.PostForm("repoCode")
	repoName := c.PostForm("repoName")
	if repoName == "" || repoCode == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := model.Repo{
		RepoCode: repoCode,
		RepoName: repoName,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "仓库添加失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "仓库添加成功",
		})
		return
	}
}
